package com.wxxymakers.grademark.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxxymakers.grademark.exception.TipServiceException;
import com.wxxymakers.grademark.model.entity.WxItemRank;
import com.wxxymakers.grademark.model.mapper.WxItemRankMapper;
import com.wxxymakers.grademark.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2018/12/29 23:03
 * @DESCRIBE
 */
@Service
public class WxItemRankService {

    @Resource
    private WxItemRankMapper rankMapper;

    @Transactional
    public boolean add(WxItemRank rank) {
        if (isExist(rank.getItemId(), rank.getName())) {
            throw new TipServiceException("已存在相同的项目等级");
        }
        return rankMapper.insert(rank) > 0;
    }

    @Transactional
    public boolean delete(int id) {
        return rankMapper.deleteById(id) > 0;
    }

    @Transactional
    public boolean deleteByIid(int itemId) {
        QueryWrapper<WxItemRank> wrapper = new QueryWrapper<>();
        wrapper.eq("item_id", itemId);
        try {
            rankMapper.delete(wrapper);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Transactional
    public boolean change(WxItemRank rank) {
        return rankMapper.updateById(rank) > 0;
    }

    public WxItemRank get(int id) {
        return rankMapper.selectById(id);
    }

    /**
     * 根据项目id和级别名判断是不是已经存在项目的记录
     * @param itemId 项目id
     * @param name 级别名
     */
    public boolean isExist(int itemId, String name) {
        return rankMapper.countByItemIdAndName(itemId, name) > 0;
    }

    public Page<WxItemRank> page(int page, int limit, WxItemRank query) {
        QueryWrapper<WxItemRank> wrapper = new QueryWrapper<>(query);
        wrapper.orderByDesc("id");

        int total = rankMapper.selectCount(wrapper);
        if (total > 0) {
            List<WxItemRank> ranks = rankMapper.selectPage(PageUtils.rowBounds(page, limit), wrapper).getRecords();
            return new PageImpl<>(ranks, new PageRequest(page - 1, limit), total);
        }
        return null;
    }
}
